package com.huifaapp.mall.selectImage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.BaseActivity;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class PhoneConfirmActivity extends BaseActivity {
    String path;
    ImageView imageView;
    ImageLoader imageLoader;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        initdata();
        init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_phone_confirm;
    }

    @Override
    protected void initialize() {}
    @Override
    protected void initView() {}

    private void init() {
        imageLoader = ImageLoader.getInstance();
        imageView = (ImageView) findViewById(R.id.ivphone);
        imageLoader.displayImage("file://" + path, imageView, new DisplayImageOptions.Builder().considerExifParams(true).build());
    }

    public void initdata() {
        Intent intent = getIntent();
        if (intent != null) {
            path = intent.getStringExtra("path");
            if (path == null || "".equals(path) || !new File(path).exists()) {
                showMsg("系统读取图片时出错！");
                finish();
            }
            return;
        }
        showMsg("系统读取图片时出错！");
        finish();
    }

    public void onAction(View v) {
        switch (v.getId()) {
            case R.id.ibIm_back:
            case R.id.ibIm_back2:
                finish();
                break;
            case R.id.btnPhonetrim:
                if (path != null && (new File(path).exists())) {
                    Intent intent = new Intent(this, CropImageActivity.class);
                    intent.putExtra("path", path);
                    intent.putExtra("IsUpload", false);
                    intent.putExtra("maintainAspectRatio", false);
                    startActivityForResult(intent, REQCODE_CROPIMAGE);
                }
                break;
            case R.id.btnPhoneSend:
                new ImageCompressionThread(path, RootFile.getCacheFiles().getPath()).start();
                break;
        }
    }

    LocalImageThread.ILocalImageAsyncTask localImageAsyncTaskListener = new LocalImageThread.ILocalImageAsyncTask() {
        @Override
        public void UIUpdate(String path, Bitmap bitmap, ImageView imageView) {
            imageView.setImageBitmap(bitmap);
        }
    };

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        switch (arg0) {
            case REQCODE_CROPIMAGE:
                if (arg2 == null) {
                    return;
                }
                String TrimPath = arg2.getStringExtra("path");
                new ImageCompressionThread(TrimPath, RootFile.getCacheFiles().getPath()).start();
                break;
        }
    }

    /**
     * 图片压缩
     *
     * @author Administrator
     *
     */
    class ImageCompressionThread extends Thread {
        String path;
        String putPath;

        public ImageCompressionThread(String path, String putPath) {
            this.putPath = putPath;
            this.path = path;
        }

        @Override
        public void run() {
            super.run();
            if (!new File(path).exists())
                return;
            File putPathFile = new File(putPath);
            if (!putPathFile.exists())
                putPathFile.mkdirs();
            String imageName = String.valueOf(System.currentTimeMillis());
            try {
                imageName = new Md5FileNameGenerator().generate(imageName);
                String imagepath;
                if (!path.endsWith(".gif")) {
                    imagepath = putPath + "/" + imageName + ".jpg";
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(imagepath));
                    Bitmap bt = BitmapCondense.Condense(400, 400, path);
                    ByteArrayInputStream isBm = new ByteArrayInputStream(BitmapCondense.SavePicIn(bt, 200).toByteArray());
                    bt = BitmapFactory.decodeStream(isBm, null, null);
                    bt.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    bt = null;
                    isBm.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    Message message = handler.obtainMessage();
                    message.what = HANDLERTRIM;
                    message.obj = imagepath;
                    handler.sendMessage(message);
                }
            } catch (FileNotFoundException e1) {
                handler.sendEmptyMessage(HANDLERERROR_COMPRESSION);
            } catch (IOException e) {
                handler.sendEmptyMessage(HANDLERERROR_COMPRESSION);
            }
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLERTRIM:
                    Intent data = new Intent();
                    data.putExtra("path", (String) msg.obj);
                    setResult(RESCODE_PATH, data);
                    finish();
                    break;
                case HANDLERERROR_COMPRESSION:
                    showMsg("压缩图片时出现错误！");
                    finish();
                    break;
            }
        };
    };
    public static final int REQCODE_CROPIMAGE = 4;
    public static final int RESCODE_PATH = 1;
    public static final int HANDLERTRIM = 1;
    public static final int HANDLERERROR_COMPRESSION = 2;

}
